package com.boot.weirdor.facade.shiro.realm;

import com.boot.weirdor.common.utill.DigestUtils;
import com.boot.weirdor.facade.shiro.bean.ShiroUser;
import com.boot.weirdor.module.entity.User;
import com.boot.weirdor.module.service.IRoleService;
import com.boot.weirdor.module.service.IUserService;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.Set;

/**
 * Created by weirdor on 2017/8/17.
 */
public class AuthRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(AuthRealm.class);


    @Autowired
    private IUserService personFacadeApi;

    @Autowired
    private IRoleService roleService;

    /**
     * 权限认证
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(shiroUser.getRoles());
        info.addStringPermissions(shiroUser.getUrls());

        return info;
    }

    /**
     * 登录认证
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("shiro开始认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        User person = personFacadeApi.selectByUserName(username);
        if (null == person) {
            throw new UnknownAccountException("账号不存在");
        }
        //账户未启用
        if (person.getStatus() == 1) {
            return null;
        }
        Map<String, Set<String>> resourceMap = roleService.selectResourceMapByUserId(person.getId());
        Set<String> urls = resourceMap.get("urls");
        Set<String> roles = resourceMap.get("roles");
        ShiroUser shiroUser = new ShiroUser();
        shiroUser.setId(person.getId());
        shiroUser.setRealName(person.getName());
        shiroUser.setUsername(person.getLoginName());
        shiroUser.setHealUrl(person.getHeadUrl());
        shiroUser.setShowName(StringUtils.isBlank(person.getName()) ? person.getLoginName() : person.getName());
        shiroUser.setUrls(urls);
        shiroUser.setRoles(roles);
        logger.info("用户信息"+shiroUser);
        System.out.print(shiroUser);
        // 查询用户角色
        // 当验证都通过后，把用户信息放在session里
        this.setSession("userSession", shiroUser);
        this.setSession("userSessionId", shiroUser.getId());
        return new SimpleAuthenticationInfo(shiroUser, person.getPassword().toCharArray(), ByteSource.Util.bytes(person.getSalt()), getName());
    }

    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }
}
